﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;

namespace Motar.Desktop.Controls
{

    /// <summary>
    /// 
    /// </summary>
    [ContentProperty("Templates")]
    public class DataTemplateChoices : DataTemplateSelector
    {
        /// <summary>
        /// 
        /// </summary>
        private readonly List<DataTemplate> _templates = new List<DataTemplate>();

        /// <summary>
        /// 
        /// </summary>
        public List<DataTemplate> Templates
        {
            get { return _templates; }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="item"></param>
        /// <param name="container"></param>
        /// <returns></returns>
        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            Type objectType = item.GetType();

            DataTemplate dataTemplate = Templates.FirstOrDefault(x => MatchViaDataType(x, objectType));

            return dataTemplate ?? base.SelectTemplate(item, container);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dataTemplate"></param>
        /// <param name="objectType"></param>
        /// <returns></returns>
        private static bool MatchViaDataType(DataTemplate dataTemplate, Type objectType)
        {
            Type type = dataTemplate.DataType as Type;

            return type != null && type.IsAssignableFrom(objectType);
        }
    }
}
